const {cosConfig} = require('../env');
var COS = require('cos-nodejs-sdk-v5');

const cosUtil = {
    cos: null,
    Bucket: cosConfig.Bucket,  // 存储桶名称
    Region: cosConfig.Region,   // 存储桶区域
 
    // 初始化配置
    init(config) {
        if(config){
            this.Bucket = config.Bucket || this.Bucket;
            this.Region = config.Region || this.Region;
            this.Prefix = config.Prefix || this.Prefix;
        }
 
        // 下面两个密钥，需要在腾讯云获取(具体在用户-访问设置进行配置获取)
        this.cos = new COS({
            SecretId: cosConfig.SecretId,   // 密钥id
            SecretKey: cosConfig.SecretKey  // 密钥key
        });
    },
 
    putObject(param) {
        this.init();
        return new Promise((resolve, reject) => {
            this.cos.putObject({
                Bucket: this.Bucket, /* 必须 */
                Region: this.Region,    /* 必须 */
                Key: param.key,              /* 必须 */
                Body: param.buffer, /* 必须 */
            }, function (err, data) {
                if (err) {
                    reject(err);
                    return;
                }
                resolve(data)
            });
        })
    }
}
 

module.exports = cosUtil;
